package com.cloudsail.domain.strategy.service.rule.chain.factor;

import com.cloudsail.domain.strategy.model.entity.StrategyEntity;
import com.cloudsail.domain.strategy.repository.IStrategyRepository;
import com.cloudsail.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author CloudSailNeverSee
 * @create 2024-10-22 20:11
 * @description 责任链工厂
 */
@Service
public class DefaultChainFactory {
    // Map依赖注入
    private final Map<String, ILogicChain> logicChainGroup;
    protected IStrategyRepository repository;
    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository) {
        this.logicChainGroup = logicChainGroup;
        this.repository = repository;
    }
    /**
     * 通过策略ID，构建责任链
     *
     * @param strategyId 策略ID
     * @return LogicChain，责任链开头
     */
    public ILogicChain openLogicChain(Long strategyId) {
        StrategyEntity strategy = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategy.ruleModels();

        // 如果未配置策略规则，则只装填一个默认责任链
        if (null == ruleModels || 0 == ruleModels.length) return logicChainGroup.get("default");

        // 按照配置顺序装填用户配置的责任链；rule_blacklist、rule_weight (顺序实际上由数据库决定)
        ILogicChain iLogicChain = logicChainGroup.get(ruleModels[0]); // 责任链链头，类似于头结点吧
        ILogicChain current = iLogicChain;
        for (int i = 1; i < ruleModels.length; i++) {
            current = current.appendNext(logicChainGroup.get(ruleModels[i]));
        }
        // 最后需要装填兜底策略
        current.appendNext(logicChainGroup.get("default"));
        return iLogicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /** 抽奖奖品ID - 内部流转使用 */
        private Integer awardId;
        /**  */
        private String logicModel;
        /**
         * 抽奖奖品规则
         */
        private String awardRuleValue;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;

        private final String info;

    }
}
